package com.etime.shycourse.services.account.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.etime.shycourse.dao.SettlementMapper;
import com.etime.shycourse.dto.SettlementDto;
import com.etime.shycourse.dto.SysUserDto;
import com.etime.shycourse.pojo.Settlement;
import com.etime.shycourse.pojo.SysUser;
import com.etime.shycourse.services.account.interfaces.AccountFinanceService;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.RichTextString;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * @Author liukang
 * @Date 2022/7/19 9:24
 */
@Service
public class AccountFinanceServiceImpl implements AccountFinanceService {
    @Autowired
    private SettlementMapper settlementMapper;



    @Override
    public Page<SettlementDto> getAllSettlements(int settlementpay, long pagenum, long pagesize, int settlementtype) {

        if(settlementtype==2||settlementtype==3){
            Page<SettlementDto> settlementDtoPage = new Page<>(pagenum, pagesize);
            QueryWrapper<SettlementDto> settlementDtoQueryWrapper = new QueryWrapper<>();
            if(settlementtype!=0){
                settlementDtoQueryWrapper.eq("settlementtype",settlementtype);
            }
            settlementDtoQueryWrapper.eq("settlementpay",settlementpay);
            settlementDtoQueryWrapper.isNotNull("userid");
            settlementDtoQueryWrapper.gt("settlementuserid",0);
            Page<SettlementDto> settlements = settlementMapper.getSettlements(settlementDtoPage,settlementDtoQueryWrapper);
            return settlements;
        }else if(settlementtype==1){
            Page<SettlementDto> settlementDtoPage = new Page<>(pagenum, pagesize);
            QueryWrapper<SettlementDto> settlementDtoQueryWrapper2 = new QueryWrapper<>();
            if(settlementtype!=0){
                settlementDtoQueryWrapper2.eq("settlementtype",settlementtype);
            }
            settlementDtoQueryWrapper2.eq("settlementpay",settlementpay);
            settlementDtoQueryWrapper2.isNotNull("orgid");
            settlementDtoQueryWrapper2.lt("settlementuserid",0);
            Page<SettlementDto> orgsettlements = settlementMapper.getOrgSettlements(settlementDtoPage,settlementDtoQueryWrapper2);
            return orgsettlements;
        }

        return null;




    }


    /*
    * 获取所有结算信息
    * */
    @Override
    public Page<SettlementDto> findUserAndSettlementInfo(int id, int settlementpay, long pagenum, long pagesize) {

        List<SettlementDto> settlementDetails= settlementMapper.getSettlementDetailsByUserId(id, settlementpay, (pagenum-1)*pagesize, pagesize);
        Page<SettlementDto> page = new Page<>(pagenum,pagesize);
        page.setRecords(settlementDetails);
        int settlementCount = settlementMapper.getSettlementCount(id, settlementpay);
        page.setTotal(settlementCount);

        return page;
    }

    @Override
    public List<SettlementDto> getUserAndSettlementInfo(int id, int settlementpay) {
        List<SettlementDto> settlementDetails= settlementMapper.findSettlementDetailsByUserId(id, settlementpay);
        return settlementDetails;
    }

    /*
    * 支付提成订单
    * */
    @Override
    @Transactional
    public int pay(int [] settlementids) {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        String format = simpleDateFormat.format(date);
        int i=0;
        for (int settlementid : settlementids) {
             i = settlementMapper.updateSettlements(settlementid,format);
            if(i<=0){
                i=0;
                break;
            }
        }
        System.out.println(i);
        return i;
    }


    @Override
    public Page<Date> getDateList(long pagenum, long pagesize, int settlementpay) {
        Page<Date> datePage = new Page<>(pagenum, pagesize);
        QueryWrapper<Date> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("settlementpay",settlementpay);
        settlementMapper.getDateList(datePage,queryWrapper);

        return settlementMapper.getDateList(datePage,queryWrapper);
    }

        /*
        * 根据日期查询settlement结算信息
        * */

    public List<SettlementDto> getSettlementByDate( int settlementpay,String settlementtime,int id,String type) {
        System.out.println("settlementtime"+settlementtime);
        System.out.println("settlementtime"+settlementpay);
//        Page<SettlementDto> page = new Page<>(pagenum, pagesize);
        QueryWrapper<SettlementDto> queryWrapper = new QueryWrapper<>();
        if("user".equals(type)){
            queryWrapper.eq("settlementpay",settlementpay);
            queryWrapper.eq("settlementtime",settlementtime);
            queryWrapper.eq("settlementuserid",id);
            queryWrapper.isNotNull("u.userid");
            return settlementMapper.getSettlementByDate(queryWrapper);
        }else if("org".equals(type)){
            queryWrapper.eq("settlementpay",settlementpay);
            queryWrapper.eq("settlementtime",settlementtime);
            queryWrapper.eq("settlementuserid",id);
            queryWrapper.isNotNull("org.orgid");
            return settlementMapper.orgGetSettlementByDate(queryWrapper);
        }
            return null;
    }
    /*
    * 根据userid查询符合条件的settlement日期列表
    * */
    @Override
    public Page<Date> findDateList(long pagenum,long pagesize,int settlementpay, Integer id,String type) {
        Page<Date> datePage = new Page<>(pagenum, pagesize);
        QueryWrapper<Date> dateQueryWrapper = new QueryWrapper<>();
        if("user".equals(type)){
            dateQueryWrapper.eq("settlementpay",settlementpay);
            dateQueryWrapper.eq("settlementuserid",id);
            dateQueryWrapper.isNotNull("u.userid");
            return settlementMapper.findDateList(datePage,dateQueryWrapper);
        }else if("org".equals(type)){
            dateQueryWrapper.eq("settlementpay",settlementpay);
            dateQueryWrapper.eq("settlementuserid",id);
            dateQueryWrapper.isNotNull("org.orgid");
            return settlementMapper.orgFindDateList(datePage,dateQueryWrapper);
        }
        return null;
    }


    /*
    * 导出支付打印单excel
    * */
    @Override
    public void print(int[] settlementids, HttpServletResponse response,String type) {


        HSSFWorkbook workbook = new HSSFWorkbook();//创建一个workbook即创建一个工作簿（一个excel表）
        HSSFSheet sheet = workbook.createSheet();//创建一个sheet
        HSSFRow row = sheet.createRow(0);//创建一行 下标从0开始
        //表头
        row.createCell(0).setCellValue("序号");
        sheet.setColumnWidth(0, 6*256);
        row.createCell(1).setCellValue("课程名称");
        sheet.setColumnWidth(1, 40*256);
        row.createCell(2).setCellValue("消费用户");
        sheet.setColumnWidth(2, 12*256);
        row.createCell(3).setCellValue("订单价格（单位：元）");
        sheet.setColumnWidth(3, 24*256);
        row.createCell(4).setCellValue("提成金额（单位：元）");
        sheet.setColumnWidth(4, 24*256);
        row.createCell(5).setCellValue("结算类型");
        sheet.setColumnWidth(5, 16*256);
        row.createCell(6).setCellValue("提成者姓名/机构名");
        sheet.setColumnWidth(6, 20*256);
        row.createCell(7).setCellValue("总计提成金额（单位：元）");
        sheet.setColumnWidth(7, 24*256);


        //如果打印的数据条数超过两条 合计时才需合并单元格
        if(settlementids.length>=2){
            CellRangeAddress cellAddresses = new CellRangeAddress(1,settlementids.length,7,7);
            sheet.addMergedRegion(cellAddresses);
        }

        //如果类型是用户
        if("user".equals(type)){
            double total = 0;
            for(int i=0;i<settlementids.length;i++){
                SettlementDto settlement = settlementMapper.getSettlement(settlementids[i]);
                total=total+settlement.getSettlementamount().doubleValue();
            }
            for(int i=0;i<settlementids.length;i++){
                SettlementDto settlement = settlementMapper.getSettlement(settlementids[i]);
                HSSFRow row1= sheet.createRow(i + 1);//创建行  上面有下标为0的了 所以这里下标从1开始
                row1.createCell(0).setCellValue(i+1);
                row1.createCell(1).setCellValue(settlement.getOdcoursename());
                row1.createCell(2).setCellValue(settlement.getOrderusertruename());
                row1.createCell(3).setCellValue(settlement.getSettlementsale().toString());
                row1.createCell(4).setCellValue(settlement.getSettlementamount().toString());
                if(settlement.getSettlementtype()==1)
                    row1.createCell(5).setCellValue("教育机构结算");
                else if(settlement.getSettlementtype()==2)
                    row1.createCell(5).setCellValue("销售人员结算");
                else if(settlement.getSettlementtype()==3)
                    row1.createCell(5).setCellValue("教师结算");
                row1.createCell(6).setCellValue(settlement.getUsertruename()+"（提成者姓名）");
                row1.createCell(7).setCellValue(total);
            }
            System.out.println(total);
        }else if("org".equals(type)){/*如果类型是机构*/
            double total = 0;
            for(int i=0;i<settlementids.length;i++){
                SettlementDto settlement = settlementMapper.getSettlement(settlementids[i]);
                total=total+settlement.getSettlementamount().doubleValue();
            }
            for(int i=0;i<settlementids.length;i++){
                SettlementDto orgSettlement = settlementMapper.getOrgSettlement(settlementids[i]);
                HSSFRow row1= sheet.createRow(i + 1);//创建行  上面有下标为0的了 所以这里下标从1开始
                row1.createCell(0).setCellValue(i+1);
                row1.createCell(1).setCellValue(orgSettlement.getOdcoursename());
                row1.createCell(2).setCellValue(orgSettlement.getOrderusertruename());
                row1.createCell(3).setCellValue(orgSettlement.getSettlementsale().toString());
                row1.createCell(4).setCellValue(orgSettlement.getSettlementamount().toString());
                if(orgSettlement.getSettlementtype()==1)
                    row1.createCell(5).setCellValue("教育机构结算");
                else if(orgSettlement.getSettlementtype()==2)
                    row1.createCell(5).setCellValue("销售人员结算");
                else if(orgSettlement.getSettlementtype()==3)
                    row1.createCell(5).setCellValue("教师结算");
                row1.createCell(6).setCellValue(orgSettlement.getOrgname()+"(机构名）");
                row1.createCell(7).setCellValue(total);
            }
            System.out.println(total);
        }


        try{
            //响应到浏览器
            //getBytes("utf-8")使用指定的的字符集编码成byte序列
            //构造方法：String(byte[] bytes, String charsetName)   通过使用指定的 charset 解码指定的 byte 数组，构造一个新的 String。
            String fileName = new String("提成支付确认单.xls".getBytes("UTF-8"), "iso8859-1");
            System.out.println(fileName);
            response.setHeader("content-Disposition","attachment;filename="+fileName);//设置以附件形式下载
            ServletOutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
        }catch (Exception e){
            e.printStackTrace();
        }

    }


}
